<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">{{ `共${page.total}条记录` }}</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportDate"
            >导出</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="showDialog = !showDialog"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            align="center"
            :formatter="employeeFormatter"
          >
            <!-- 不要乱用语法 -->
            <!-- <template v-slot="{ row }">
              <div>
                {{ row.id }}
              </div>
            </template> -->
          </el-table-column>
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template :v-slot="{ row }">
              <el-switch
                value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="roleclick(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="del(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 3.75rem"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :current-page.sync="page.page"
            :page-size="page.size"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置组件 -->
    <AddEmployee :showDialog.sync="showDialog"></AddEmployee>
    <AssignRole
      :showRoleDialog.sync="showRoleDialog"
      :userId="userId"
      :roleList="roleList"
      ref="assignRole"
    ></AssignRole>
    <Permission></Permission>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employee'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import Permission from '../permission'
import { getRoleList } from '@/api/role'

export default {
  created() {
    this.getEmployeeList()
  },
  components: { AddEmployee, AssignRole, Permission },
  data() {
    return {
      list: [], //  接收数组,
      roleList: [],
      userId: null,
      page: {
        page: 1,
        size: 10,
        total: 0 //  总数
      },
      loading: false,
      showDialog: false, //  默认关闭弹出层 add
      showRoleDialog: false //  默认关闭弹出层 角色 AssignRole
    }
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows

      this.page.total = total
      this.loading = false
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    employeeFormatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue)

      return obj ? obj.value : '未知'
    },
    async del(data) {
      try {
        await this.$confirm('确认要删除吗?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        await delEmployee(data.id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportDate() {
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      // 导入 excel
      import('@/vendor/Export2Excel').then(async (excel) => {
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total
        })
        console.log(rows)
        //   rows username: '管理员',
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          // header: ['姓名', '工资'],
          // data: [
          //   ['张三', 1000],
          //   ['王文英', 2000]
          // ],
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    //  [{}]  [[]]
    formatJson(headers, rows) {
      //  姓名: 'username', username: '管理员',
      return rows.map((item) => {
        //   rows {username: '管理员'},
        return Object.keys(headers).map((key) => {
          //  [ '姓名'  '入职日期']
          // 需要判断 字段
          return item[headers[key]]
        })
      })
    },
    async roleclick(id) {
      this.showRoleDialog = true
      // 获取id调取接口

      const { rows } = await getRoleList({ page: 1, pagesize: 20 })
      // console.log(rows)
      // 获取所有的角色列表
      this.roleList = rows
      // 调用子组件的方法
      this.$refs.assignRole.getUserDetailByid(id)
    }
  }
}
</script>

<style>
</style>